/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { BottomAction } from '@/components';
import { Button, message, Form, Popconfirm, InputNumber, Empty } from 'antd';
import pageTabUtil from '@/utils/pageTabUtil';
import { defaultFormatResult, useRequest } from '@/hooks';
import { useFormChange } from '@/pages/RecruitEmail/hooks';
import { history } from 'umi'
import { CollapseHeader, LimitInput, AccountTable, PayrollComputationTable } from '../components';
import styles from './index.less';
import { completeHandover, getLeavePayroll, generateLeavePayroll } from '../../service';
import { LEAVE_STATUS_OBJ } from '../../dictionary';

function FinancialSettlement({ form, data, dimissionOrderId, employeeCode, ...rest }) {
    const [submitLoading, setSubmitLoading] = React.useState();
    const { hasFormChange, initialForm } = useFormChange(form);
    const [leavePayrollData, setLeavePayrollData] = React.useState();
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const { getFieldDecorator, validateFields } = form;
    // const dataSource = React.useMemo(() => {
    //     const { matterDetail } = data;
    //     const handlerDetail = matterDetail?.find(m => m.handoverType === LEAVE_STATUS_OBJ.FINANCIAL_SETTLEMENT);
    //     if (handlerDetail) {
    //         return handlerDetail?.handoverAccount;
    //     }
    //     return [];
    // }, [data]);
    // 获取薪资总额
    const params2 = {
        employeeCode,
        organizationCode: data?.dimissionOrderVO.companyCode
    };
    const { loading: leavePayrollLoading } = useRequest(() => getLeavePayroll(params2), {
        formatResult: res => {
            // 加个判断防止配置财务清算结果不包含薪资时，这个接口万一报错不展示
            if (res && data?.handoverSettings.containSalaryFlag === 1) {
                const { code, data: data2, msg } = res;
                initialForm();
                if (code === 10000) {
                    setLeavePayrollData(data2);
                } else {
                    message.error(msg);
                }
            }
            return undefined;
        }
    });
    const attendList = React.useMemo(() => {
        const list = [];
        if (data.matterDetail) {
            const { handoverHolidays } = data.matterDetail[0];
            const len = handoverHolidays.length;
            if (len > 0) {
                for (let i = 0; i < len; i += 1) {
                    const { holidayCode, holidayName, discountingDurationUpperLimit } = handoverHolidays[i];
                    list.push({
                        attendItemCode: `${holidayCode}_withdrawal`,
                        attendItemName: holidayName,
                        attendValue: discountingDurationUpperLimit,
                        salaryType: 1
                    });
                }
            }
        }
        return list;
    }, [data]);
    // 刷新薪资
    const param3 = {
        employeeCode,
        settleTimeType: data?.matterDetail[0].settlementTimeType ?? 1,
        organizationCode: data?.dimissionOrderVO.companyCode,
        compensation: data?.dimissionOrderVO.compensation,
        attendList
    };
    const { run: generateLeavePayrollRun, loading: generateLeavePayrollLoading } = useRequest(
        () => generateLeavePayroll(param3),
        {
            manual: true,
            formatResult: res => {
                if (res) {
                    const { code, data: data3, msg } = res;
                    if (code === 10000) {
                        setLeavePayrollData(data3);
                        message.success('已获取最新的薪资数据');
                    } else {
                        message.error(msg);
                    }
                }
                return undefined;
            }
        }
    );

    // 查询、刷新薪资数据自动填入总计
    React.useMemo(() => {
        if (leavePayrollData && leavePayrollData.payrollList && data?.handoverSettings.containSalaryFlag === 1) {
            const { payrollList } = leavePayrollData;
            let sum = 0;
            if (payrollList && payrollList.length > 0) {
                for (let i = 0, len = payrollList.length; i < len; i += 1) {
                    sum += Number(payrollList[i].encryptTotalPayAmt);
                }
            }
            // 经济补偿金是实发薪资里面的一部分
            form.setFieldsValue({ total: sum.toFixed(2) });
        } else {
            form.setFieldsValue({ total: data?.dimissionOrderVO.compensation });
        }
    }, [leavePayrollData, data]);
    const handleSubmit = () => {
        const { matterDetail } = data;
        const handlerDetail = matterDetail?.find(m => m.handoverType === LEAVE_STATUS_OBJ.FINANCIAL_SETTLEMENT);
        if (!handlerDetail) {
            message.error('未查询到财务清算详情');
            return;
        }
        validateFields(async (err, values) => {
            if (err) {
                return;
            }
            // if (!leavePayrollData.payrollList || !leavePayrollData.payrollList[0].encryptTotalAmt) {
            //     message.warning('财务清算存在未结款项，请等待相关数据满足结算条件', 3);
            //     return;
            // }
            try {
                setSubmitLoading(true);
                const { code, msg } = await completeHandover({
                    id: handlerDetail?.id,
                    dimissionOrderId,
                    handoverType: LEAVE_STATUS_OBJ.FINANCIAL_SETTLEMENT,
                    total: values.total ?? 0,
                    ...values
                });
                if (code === 10000) {
                    message.success(
                        `已完成财务清算，将${
                            data.matterDetail[0].settlementTimeType === 2 ? '立即结算' : '随下一个发薪日统一结算'
                        }`,
                        3
                    );
                    history.replace('/office/personnelManagement/onboardAndLeave/leaveManagement/list');
                } else {
                    message.error(msg);
                }
                setSubmitLoading(false);
            } catch (e) {
                setSubmitLoading(false);
            }
        });
    };
    const fullLineLayout = {
        labelCol: { span: 2 },
        wrapperCol: { span: 14 }
    };
    return (
        <Form layout="horizontal" {...fullLineLayout}>
            <CollapseHeader title="财务单据">
                <div style={{ margin: '40px 0px 60px' }}>
                    <Empty description="开发中，敬请期待" />
                </div>
            </CollapseHeader>
            {data.handoverSettings.financialSettlementType.includes(2) && (
                <CollapseHeader title="资产情况">
                    <div style={{ margin: '40px 0px 60px' }}>
                        <Empty description="开发中，敬请期待" />
                    </div>
                </CollapseHeader>
            )}
            <CollapseHeader title="财务清算">
                <div className={styles.itemBox}>
                    结算时间：
                    <span className={styles.val}>
                        {data.matterDetail[0].settlementTimeType === 2 ? '立即结算' : '随下一个发薪日统一结算'}
                    </span>
                </div>
                <div className={styles.itemBox}>薪资明细：</div>
                <PayrollComputationTable
                    containSalaryFlag={data?.handoverSettings.containSalaryFlag}
                    leavePayrollData={leavePayrollData}
                    loading={leavePayrollLoading || generateLeavePayrollLoading}
                    compensation={data?.dimissionOrderVO.compensation}
                    generateLeavePayrollRun={generateLeavePayrollRun}
                    dimissionType={data?.dimissionOrderVO.dimissionType}
                />
                <Form.Item label="总计">
                    {getFieldDecorator('total', {
                        rules: [{ required: true, message: '请输入总计金额' }]
                    })(<InputNumber placeholder="请输入" style={{ width: '200px' }} precision={2} />)}
                </Form.Item>
            </CollapseHeader>
            <CollapseHeader title="其他">
                <Form.Item label="备注">
                    {getFieldDecorator('remark', {
                        initialValue: data.matterDetail[0].remark
                    })(
                        <LimitInput
                            area
                            autoSize={{ minRows: 3, maxRows: 6 }}
                            placeholder="请填写备注"
                            maxLength={4000}
                        />
                    )}
                </Form.Item>
            </CollapseHeader>
            <BottomAction>
                {hasFormChange() ? (
                    <Popconfirm
                        title={
                            <>
                                当前页面存在改动信息暂未提交，
                                <br />
                                确定离开此页面？
                            </>
                        }
                        arrowPointAtCenter
                        onConfirm={() => pageTabUtil.goBack()}
                        okText="确定"
                        cancelText="取消"
                    >
                        <Button style={{ marginRight: 8 }}>取消</Button>
                    </Popconfirm>
                ) : (
                    <Button onClick={() => pageTabUtil.goBack()}>取消</Button>
                )}
                <Button type="primary" onClick={handleSubmit} loading={submitLoading}>
                    确定
                </Button>
            </BottomAction>
        </Form>
    );
}

export default Form.create()(FinancialSettlement);
